from ..model.student_model import StudentCreate, StudentUpdate, StudentResponse
from database import get_db
from database import Base
from sqlalchemy import Column, Integer, String, Date


# 定义学生表的 SQLAlchemy 模型
class Student(Base):
    __tablename__ = "students"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    age = Column(Integer)
    comment = Column(String, nullable=True)
    birth_date = Column(Date)
    gender = Column(String)


class StudentService:
    def __init__(self):
        self.db = next(get_db())

    def create(self, student: StudentCreate) -> StudentResponse:
        """创建新学生"""
        db_student = Student(**student.dict())
        self.db.add(db_student)
        self.db.commit()
        self.db.refresh(db_student)
        return StudentResponse.from_orm(db_student)

    def read(self, student_id: int) -> StudentResponse:
        """获取单个学生"""
        return self.db.query(Student).filter(Student.id == student_id).first()

    def read_all(self) -> list[StudentResponse]:
        """获取所有学生"""
        return self.db.query(Student).all()

    def update(self, student_id: int, student: StudentUpdate) -> StudentResponse:
        """更新学生信息"""
        db_student = self.db.query(Student).filter(Student.id == student_id).first()
        if not db_student:
            return None
        for key, value in student.dict(exclude_unset=True).items():
            setattr(db_student, key, value)
        self.db.commit()
        self.db.refresh(db_student)
        return StudentResponse.from_orm(db_student)

    def delete(self, student_id: int) -> bool:
        """删除学生"""
        db_student = self.db.query(Student).filter(Student.id == student_id).first()
        if not db_student:
            return False
        self.db.delete(db_student)
        self.db.commit()
        return True
